﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Framework
{
    /// <summary>
    /// 自定义Http上下文
    /// </summary>
    public class HttpContext
    {
        private HttpRequest request;
        /// <summary>
        /// Http请求对象
        /// </summary>
        public HttpRequest Request
        {
            get { return request; }
        }

        public HttpResponse response;

        /// <summary>
        /// Http响应对象
        /// </summary>
        public HttpResponse Response
        {
            get { return response; }
        }


        public HttpContext(IFeatureCollection features)
        {
            this.request = new HttpRequest(features);
            this.response = new HttpResponse(features);
        }
    }

    /// <summary>
    /// 自定义Http请求类
    /// </summary>
    public class HttpRequest
    {
        private readonly IHttpRequestFeature _feature;
        public HttpRequest(IFeatureCollection features)
        {
            _feature = features.Get<IHttpRequestFeature>();
        }
        public Uri Url
        {
            get { return _feature.Url; }
        }
        public NameValueCollection Headers
        {
            get { return _feature.Headers; }
        }
        public Stream Body
        {
            get { return _feature.Body; }
        }
    }

    /// <summary>
    /// 自定义Http响应类
    /// </summary>
    public class HttpResponse
    {
        private readonly IHttpResponseFeature _feature;
        public HttpResponse(IFeatureCollection features)
        {
            _feature = features.Get<IHttpResponseFeature>();
        }
        public NameValueCollection Headers
        {
            get { return _feature.Headers; }
        }
        public Stream Body
        {
            get { return _feature.Body; }
        }
        public int StatusCode
        {
            get { return _feature.StatusCode; }
            set { _feature.StatusCode = value; }
        }
    }

    public static partial class Extensions
    {
        /// <summary>
        /// 为HttpResponse对象扩展响应输出方法
        /// </summary>
        /// <param name="response">HttpResponse</param>
        /// <param name="contents">输出内容</param>
        /// <returns>Task</returns>
        public static void Write(this HttpResponse response, string contents)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(contents);
            response.Body.Write(buffer, 0, buffer.Length);
        }

        /// <summary>
        /// 为HttpResponse对象扩展响应输出方法
        /// </summary>
        /// <param name="response">HttpResponse</param>
        /// <param name="contents">输出内容</param>
        /// <returns>Task</returns>
        public static Task WriteAsync(this HttpResponse response, string contents)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(contents);
            return response.Body.WriteAsync(buffer, 0, buffer.Length);
        }
    }
}
